package com.auxgroup.smarthome.inner.repo;

import com.auxgroup.smarthome.inner.entity.DeviceModelInfoEntity;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by niuGuangzhe on 2017/8/8.
 */
public class DeviceModelInfoRepoSpec {
    public static Specification<DeviceModelInfoEntity> findByModelAndModelItemAndStatus(final String modelName,
                                                                                        final String modelItemName) {
        return new Specification<DeviceModelInfoEntity>() {

            @Override
            public Predicate toPredicate(Root<DeviceModelInfoEntity> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<Predicate>();

                predicates.add(criteriaBuilder.equal(root.<Boolean>get("trash"), 0));
                if (modelName != null && !modelName.equals("")) {
                    predicates.add(criteriaBuilder.like(root.<String>get("model"), "%"+modelName+"%"));
                }

                if (modelItemName != null && !modelItemName.equals("")) {
                    predicates.add(criteriaBuilder.like(root.<String>get("modelItem"), "%"+modelItemName+"%"));
                }

                return criteriaQuery.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
            }
        };

    }

}
